<?php

namespace PAT\CartBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use \PAT\CartBundle\Entity;
use PAT\UserBundle\Entity\Address;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Cookie;
use PAT\CartBundle\Entity\PaymentMode;
use PAT\CartBundle\Entity\Command;

class CartController extends Controller
{
     /**
     * @Route("/cart/{name}")
     * @Template()
     */
    public function indexAction($name)
    {
        return $this->render('PATCartBundle:Cart:index.html.twig', array('name' => $name));
    }
    
    public function fooAction()
    {	
        return $this->render('PATCartBundle:Default:layout.html.twig');
    }
    
    //Affichage des articles, quantités, toussa.
    public function displayAction()
    {
        $session = $this->getRequest()->getSession();
        $user = $this->container->get("security.context")->getToken()->getUser();
        $cart = $this->getCartFromSession();
        
        if($cart == null || $cart->getProductList() == null)
        {
            return $this->render('PATCartBundle:Default:emptyCart.html.twig');
        } else {
            return $this->render('PATCartBundle:Default:myCart.html.twig', array('cart' => $cart, 'user' => $user));
        }

    }
    
    //Tunnel de commandes (validation du panier)
    public function stepsAction($step, Request $request = null)
    {   
        switch($step)
        {
            case 1:
                //Liste des articles dans le panier
                $user = $this->container->get("security.context")->getToken()->getUser();
                $cart = $this->getCartFromSession();
                
                if(is_object($user) != null)
                {
                    //Si il est authentifié, on redirige vers l'etape2
                    return $this->render('PATCartBundle:Default:step2.html.twig', array('cart' => $cart, 'user' => $user));
                } else {                
                    //Sinon, on l'invite a s'authentifier
                    
                    //Mettre formulaire d'authentification (login)
                    //Avec verif, redirection vers l'inscription (register)
                    return $this->render('PATCartBundle:Default:step1.html.twig', array('user' => null, 'cart' => $cart));                 
                }
                break;
            case 2:
                //Choix des adresses de livraison et de paiement
                return $this->displayAddresseschoice();
               
                break;
            
            case 3:        
                //Choix du mode de paiement
                
                //Récupération et sauvegarde en session des adresses choisies
                $this->postBackAddresses();
                
                //Création du formulaire avec les différents modes de paiement
                $form = $this->createFormBuilder()
                        ->add('paymentMode', 'choice', array('label' => 'Mode de paiement : ', 'choices'=> array('0' => 'Carte Bancaire', '1' => 'Virement Paypal', '2' => 'Contre-remboursement') ) )
                        ->getForm();
                return $this->render('PATCartBundle:Default:step3.html.twig', array('form' => $form->createView()));
                break;
                
            case 4:
                return $this->recapCommand();
                break;
            case 5:
                return $this->saveCommand();
                break;
            default:
                break;
        }
    }
    
    private function addToCart($cart, $product)
    {
        $productExist = false;
        //On regarde si le produit existe deja dans la liste
        if($cart == null || is_object($cart))
        {
            $bool = false;
            $productList = $cart->getProductList();
            if($productList != null)
            {
                foreach($productList as $line)
                {
                    if( isset($productList[$product->getId()]) )
                    {
                        $bool = true;
                    }
                }
            }

            // Le produit existe deja dans la liste (on modifie sa quantité)
            if($bool == true) 
            {
                $productList[$product->getId()]["product"] =  array("name" => $product->getName(), 
                                                                "priceHT" => $product->getPriceHT(),
                                                                "picture" => $product->getPicture()
                                                                );
                $productList[$product->getId()]["quantity"] += 1;
            } else // Le produit n'existe pas dans la liste, on l'ajoute.
            {
                $productArray =  array("name" => $product->getName(), 
                                                                "priceHT" => $product->getPriceHT(),
                                                                "picture" => $product->getPicture()
                                                                );
                $productList[$product->getId()] = array("product" => $productArray,
                                                               "quantity" => 1);
                
            }
            $cart->setProductList($productList);
        } else 
        {
            //Si le panier possède déjà des articles
            if(is_object($cart) == false)
            {
                //On parcourt le panier pour voir si l'article y est déjà présent
                foreach($cart->getProductList() as $line)
                {
                    $productList = $cart->getProductList();
                    if( isset( $productList[$product->getId()] ) )
                    {                         
                        $productExist = true;
                    }
                }
            }

            // Si le produit existe, on modifie la quantité et on met a jour la somme.
            if($productExist == true) 
            {
                $productList = $cart->getProductList();
                $productList[$productId]["quantity"] += 1;
                $cart->setProductList($productList);
            }
            else // Si non, on ajoute une ligne dans le tableau
            {
                $productList = $cart->getProductList();
                $productList[$productId]["quantity"] = 1;
                $productList[$productId]["product"] =  array("name" => $product->getName(), 
                                                            "priceHT" => $product->getPriceHT(),
                                                            "picture" => $product->getPicture()
                                                            );
                
                $cart->setProductList($productList);
            }
        }
        
        // Mise à jour du panier en session
        $this->setCartToSession($cart);
    }
    
    public function addToCartAction($productId)
    {    
        $products = $this->getDoctrine()->getEntityManager()->getRepository('PATProductBundle:Product');
        $product = $products->find($productId);
        
        $cart = $this->getCartFromSession();
        
        $this->addToCart($cart, $product);
        
        $user = $this->container->get("security.context")->getToken()->getUser();

        if($cart == null)
        {
            return $this->render('PATCartBundle:Default:emptyCart.html.twig');
        } else {
            return $this->render('PATCartBundle:Default:myCart.html.twig', array('cart' => $cart, 'user' => $user));
        }
    }
    
    public function deleteToCartAction($productId)
    {
        //Récupération du panier en session
        $cart = $this->getCartFromSession();

        $productExist = false;
        
        if($cart != null && $cart->getProductList() != null)
        {
            //On parcourt le panier pour voir si l'article y est déjà présent qu'une seule fois
           $productList = $cart->getProductList();
           if( isset( $productList[$productId] ) && $productList[$productId]["quantity"] == 1)
           {                         
               $productExist = true;
           }
        }
        
        //Si on veut supprimer tous les articles du même ID ou si l'article n'est présent qu'une fois
        if(strpos($productId, '_') != false || $productExist == true )
        {
            $array = explode('_', $productId);
            $productId = $array[0];
            $newProductList = null;
            $productList = $cart->getProductList();

            foreach($productList as $key => $value)
                if($key != $productId && $key != 0)
                    $newProductList[$key] = array("product" =>$productList[$key]["product"], "quantity" => $productList[$key]["quantity"] );
                
            $cart->setProductList($newProductList);
        }
        else // Sinon, modifie sa quantité
        {
            $productList = $cart->getProductList();
            $productList[$productId]["quantity"] -= 1;
            $cart->setProductList($productList);
        }
        
        $user = $this->container->get("security.context")->getToken()->getUser();
        
        // On met a jour le panier en session
        $this->setCartToSession($cart);

        // On affiche le panier
        if($cart == null || $cart->getProductList() == null)
        {
            return $this->render('PATCartBundle:Default:emptyCart.html.twig');
        } else {
            return $this->render('PATCartBundle:Default:myCart.html.twig', array('cart' => $cart, 'user' => $user));
        }
    }
    
    // Ajout de la totalité d'une wishlist dans le panier
    public function addWishlistToCartAction($wishlistId){
        $em = $this->getDoctrine()->getEntityManager();
        $wishlist = $em->getRepository('PATWishlistBundle:Wishlist')->find($wishlistId);
        $products = $wishlist->getProducts();
        
        $cart = $this->getCartFromSession();

        foreach($products as $product){
            $this->addToCart($cart, $product);
        }
        
        $user = $this->container->get("security.context")->getToken()->getUser();

        if($cart == null)
        {
            return $this->render('PATCartBundle:Default:emptyCart.html.twig');
        } else {
            return $this->render('PATCartBundle:Default:myCart.html.twig', array('cart' => $cart, 'user' => $user));
        }
        
    }
    
    // On valide la commande
    public function validateAction()
    {
        $session = $this->getRequest()->getSession();
        $user = $session->get('user');
    }
    
    //Récupération du panier stocké en session
    public function getCartFromSession()
    {
        $session = $this->getRequest()->getSession();
        $cartFromSession = $session->get('cart');
        $cart = new Entity\Cart();
        $cart->setProductList($cartFromSession);
        return $cart;
    }
    
    // Mise à jour du panier en session
    public function setCartToSession($cart)
    {
       $this->getRequest()->getSession()->set("cart", $cart->getProductList());
    }
    
    
    public function displayAddresseschoice()
    {
        //Formulaire d'ajout d'une adresse
        $address = new Address();
        $user = $this->container->get("security.context")->getToken()->getUser();

        $form = $this->createFormBuilder($address)
        ->add('street', 'text', array('label' => 'Rue, Voie, Chemin', 'required' => true))
        ->add('city', 'text', array('label' => 'Ville', 'required' => true))
        ->add('postalCode', 'text', array('label' => 'Code postal', 'required' => true))
        ->add('country', 'text', array('label' => 'Pays', 'required' => true))
        ->getForm();

        //Traitement de la nouvelle adresse
        if($this->getRequest()->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if($form->isValid())
            {
                //Sauvegarde de la nouvelle adresse
                $address = $form->getData();
                $address->setUser($user);
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($address);
                $em->flush();
                return $this->redirect($this->generateUrl('pat_cart_displaysteps', array('step' => 2)));  
            }
        }   

        //Récupérations des adresses enregistrées
        $user = $this->container->get("security.context")->getToken()->getUser();
        //Si il est connecté (condition a modifier)
        if(is_object($user))
        {
            $addressArray = array();
            foreach($user->getAddresses() as $address)
            {
                $addressArray[] = array(
                                            'id' => $address->getId(),
                                            'street' => $address->getStreet(), 
                                            'city' => $address->getCity(),
                                            'postalCode' => $address->getPostalCode(),
                                            'country' => $address->getCountry()
                        );
            }
            return $this->render('PATCartBundle:Default:step2.html.twig', array('form' => $form->createView(), 'addressArray' => $addressArray));
        } else {
            return $this->render('PATUserBundle:User:layout.html.twig');
        }

    }

    public function postBackAddresses()
    {
        if($this->getRequest()->getMethod() == 'POST')
        {
            $valueAddress = $_POST['hiddenField'];
            $session = $this->getRequest()->getSession();
            $deliveryAddress = "";                 
            $arrayDelivery =  explode(".", $valueAddress);

            foreach($arrayDelivery as $i )
            {
                if( strpos($i, '_') !== false)
                {
                    $deliveryArray = explode('_', $i);
                    foreach($deliveryArray as $j)
                    {
                        if($j != 0)
                            $deliveryAddress = $j;
                    }
                }
            }

            $paymentAddress = "";
            $arrayPayment = explode('_', $valueAddress);
            foreach($arrayPayment as $i )
            {
                if( strpos($i, '.') !== false)
                {
                    $paymentArray = explode('.', $i);
                    foreach($paymentArray as $j)
                    {
                        if($j != 0)
                            $paymentAddress = $j;
                    }
                }
            }
            $session->set('addresses', array($deliveryAddress, $paymentAddress));
        }
    }
    
    public function recapCommand()
    {
        $command = new Entity\Command();
        $cart = $this->getCartFromSession();
        $paymentMode = $_POST['form']['paymentMode'];
        $paymentModeStr = '';

        if(isset($paymentMode) )
        {
            switch($paymentMode)
            {
                case '0' :
                    $paymentModeStr = 'Carte Bancaire';
                    break;
                case '1' :
                    $paymentModeStr = 'Virement Paypal';
                    break;
                case '2' :
                    $paymentModeStr = 'Contre-remboursement';
                    break;
            }
        }
        $session = $this->getRequest()->getSession();
        $addressesArray = $session->get('addresses');                
        $allAddresses = $this->getDoctrine()->getEntityManager()->getRepository('PATUserBundle:Address');
        $deliveryAddress = $addressesArray[0];
        $paymentAddress = $addressesArray[1];
        $displayArray = array();
        $totalPriceHT = 0;
        $feeRate = 19.6;

        foreach($cart->getProductList() as $productId => $array)
        {
        $products = $this->getDoctrine()->getEntityManager()->getRepository('PATProductBundle:Product');
        $prod = $products->find($productId);
        $total = $prod->getPriceHT() * $array["quantity"];
        $displayArray[] = array(
        "product" =>$prod,
        "quantity" => $array["quantity"],
        "sum" => $total,
        );
        $totalPriceHT += $total;
        }

        // Estiomation des frais de port :
        $shippingCost = $totalPriceHT * 5 / 100;

        //Calcul du prix ttc :
        $totalPriceTTC = ( ($totalPriceHT * $feeRate) + $totalPriceHT) + $shippingCost;

        //Préparation de la commande
        $this->getRequest()->getSession()->set('deliveryAddress', $deliveryAddress);
        $this->getRequest()->getSession()->set('paymentAddress', $paymentAddress);
        $this->getRequest()->getSession()->set('paymentMode', $paymentMode);
        $this->getRequest()->getSession()->set('totalPriceTTC', $totalPriceTTC);

        $commandProductList = array();
        foreach($cart->getProductList() as $productId => $array)
        {   
        $commandProductList[] = array('product' => $productId, 'quantity' => $array['quantity']);
        }
        $this->getRequest()->getSession()->set('commandProductList', $commandProductList);

        return $this->render('PATCartBundle:Default:step4.html.twig', 
                        array(
                            'displayArray' => $displayArray,
                            'shippingCost' => $shippingCost,
                            'feeRate' => $feeRate,
                            'totalPriceHT' => $totalPriceHT,
                            'totalPriceTTC' => $totalPriceTTC,
                            'paymentMode' => $paymentModeStr,
                            'deliveryAddress' => $allAddresses->find($deliveryAddress),
                            'paymentAddress' => $allAddresses->find($paymentAddress),
                        ) );
    }
    
    public function saveCommand()
    {
        $products = $this->getDoctrine()->getEntityManager()->getRepository('PATProductBundle:Product');
        $user = $this->container->get("security.context")->getToken()->getUser();
        $addresses = $this->getDoctrine()->getEntityManager()->getRepository('PATUserBundle:Address');
        $deliveryAddress = $addresses->find($this->getRequest()->getSession()->get('deliveryAddress'));
        $paymentAddress = $addresses->find($this->getRequest()->getSession()->get('paymentAddress'));
        $paymentModeStr = $this->getRequest()->getSession()->get('paymentMode');
        $paymentMode = 0;

        switch($paymentModeStr)
        {
            case 'Carte Bancaire' :
                $paymentMode = 0;
                break;
            case 'Virement Paypal' :
                $paymentModeStr = 1;
                break;
            case 'Contre-remboursement' :
                $paymentModeStr = 2;
                break;
        }

        $command = new Command();
        $command->setAddressDelivery($deliveryAddress);
        $command->setAddressPayment($paymentAddress);
        $command->setPaymentMode($paymentMode);
        $command->setUser($user);
        $command->setPaymentDate(new \DateTime(date("Y-m-d")));
        $command->setTotalPrice($this->getRequest()->getSession()->get('totalPriceTTC'));

        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($command);
        $em->flush();

        $commandProductList = $this->getRequest()->getSession()->get('commandProductList');

        foreach($commandProductList as $commandProductArray)
        {
            $commandProduct = new \PAT\CartBundle\Entity\CommandProduct();
            $commandProduct->setQuantity($commandProductArray['quantity']);
            $commandProduct->setProduct($products->find($commandProductArray['product']));
            $commandProduct->setCommand($command);
            $em->persist($commandProduct);
            $em->flush();
        }

        //Clean de la session
        $this->getRequest()->getSession()->remove('cart');
        $this->getRequest()->getSession()->remove('paymentAddress');
        $this->getRequest()->getSession()->remove('deliveryAddress');
        $this->getRequest()->getSession()->remove('commandProductList');


        return $this->render('PATCartBundle:Default:step5.html.twig');
    }
    
}

